#include "check.h"
#include "ui_check.h"
#include "widget.h"

check::check(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::check)
{
    ui->setupUi(this);
}

check::~check()
{
    delete ui;
}

void check::on_returnbtn_clicked()
{
    check::~check();
}

void check::show_time(){
    QTableView *table = ui->showresult;
    model = new QStandardItemModel(table);
    model->setHorizontalHeaderLabels(QStringList()<<"学期号" << "课程名称" ); // 设置表头

    QString workingDirectory = QDir::toNativeSeparators(QDir::current().filePath("output.txt"));
    QFile file(workingDirectory); //路径选择

    QStringList output_value;
    std::vector<int> data;
    if (file.open(QIODevice::ReadOnly)) {
        QTextStream in(&file);
        while (!in.atEnd()) {
            QString lines = in.readLine();
            QStringList fields = lines.split(','); // 使用逗号作为分隔符
            data.push_back(fields.back().toInt());
            output_value.append(fields.front());
        }
        file.close();
    } else {
        qDebug() << "Unable to open file"; // 如果无法打开文件，输出错误信息
    }

    for (int i = 0; i < 8; i++) {
        QStandardItem *item1 = new QStandardItem(QString("第%1学期").arg(i+1));
        item1->setData(QString("Description %1").arg(i+1), Qt::UserRole);
        model->setItem(i, 0, item1);
    }


    Widget *w = new Widget;
    int limit = w->getSpinbox();
    delete w;

    int mark = 0;
    int row = 0;
    for (int i = 0; i < (int)data.size(); i++) {
        QString myfields;
        do{
            mark += data[i];
            if(mark<=limit){
                myfields += output_value[i];
                myfields +="  ";
                i++;
            }else{
                i--;
                break;
            }
        }while (i < (int)data.size());
        QStandardItem *item2 = new QStandardItem();
        item2->setData(myfields, Qt::DisplayRole); // 明确指定数据的角色
        model->setItem(row, 1, item2);
        row++; // 在数据设置到模型后再增加行数
        mark = 0; // 重置mark的值
    }

    table->setModel(model);
    table->setColumnWidth(1,424);
    table->show();
}

